<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthorizationRequest;
use App\Models\User;
use Auth;
use Cache;
use JWTAuth;

class AuthorizationsController extends Controller
{
    public function store(AuthorizationRequest $request)
    {
        //获取账户数组
        $credentials = $this->generateCredentials($request);

        //生成Token
        $token = $this->generateToken($credentials);

        return $this->respondWithToken($token)->setStatusCode(201);
    }

//    public function wechatStore($type, WechatAuthorizationRequest $request)
//    {
//        $app = app('wechat.official_account');
//        $oauth = $app->oauth;
//
//        // 获取微信 OAuth 授权结果用户信息
//        $user_wechat = $oauth->user();
//        $openid = $user_wechat->getId();
//        if ($type == 'user') {
//            $user = User::where('weixin_openid', $openid)->first();
//            //如果用户存在，返回 Token
//            if ($user) {
//                $token = Auth::guard('api')->fromUser($user);
//
//                return $this->respondWithToken($token, $type)->setStatusCode(201);
//            }
//        } else {
//            $user = NewStudent::where('weixin_openid', $openid)->first();
//
//            if ($user) {
//                $token = Auth::guard('api_new_student')->fromUser($user);
//                return $this->respondWithToken($token, $type)->setStatusCode(201);
//            }
//        }
//        $result = $this->generateOpenidKey($openid);
//
//        return $this->response->array($result)->setStatusCode(201);
//    }
//
//    public function bind($type, WechatAuthorizationRequest $request)
//    {
//        //从缓存取出openid
//        $openidData = Cache::get($request->openid_key);
//        if (!$openidData) {
//            return $this->response->error('验证期已经超时，请退出重进！', 422);
//        }
//        $credentials = $this->generateCredentials($type, $request);
//        $token = $this->generateToken($type, $credentials);
//        $credentials = array_except($credentials, 'password');
//        if ($type == 'user') {
//            User::where($credentials)
//                ->update(['weixin_openid' => $openidData['openid']]);
//        } else {
//            NewStudent::where($credentials)
//                ->update(['weixin_openid' => $openidData['openid']]);
//        }
//        return $this->respondWithToken($token, $type)->setStatusCode(201);
//    }

    public function update()
    {
        $token = Auth::guard()->refresh();

        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        Auth::guard('api')->logout();

        return $this->response->noContent();
    }

    protected function generateOpenidKey($openid)
    {
        $key = 'openid_' . str_random(15);
        $expiredAt = now()->addMinutes(30);
        Cache::put($key, ['openid' => $openid], $expiredAt);
        $result = [
            'openid_key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ];
        return $result;
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard()->factory()->getTTL() * 60
        ]);
    }

    protected function generateToken($credentials)
    {
        if (!$token = Auth::guard()->attempt(array_merge($credentials, ['is_active' => 1]))) {
            return $this->response->errorUnauthorized('用户名或密码错误,或该账号未激活');
        }
        return $token;
    }

    protected function generateCredentials($request)
    {
        $credentials['password'] = $request->password;
        $username = $request->username;
        preg_match("/^1[345789]\d{9}$/", $username) ?
            $credentials['phone'] = $username :
            $credentials['name'] = $username;
        return $credentials;
    }
}
